package helperF

import (
	"reflect"
)

// TrimEmpty 删除空字符串元素
func TrimEmpty[T comparable](haystack []T) []T {
	var zero T
	results := make([]T, 0)
	for _, item := range haystack {
		if item != zero {
			results = append(results, item)
		}
	}
	return results
}

// ArrContain 检查haystack是否包含target
func ArrContain[T comparable](haystack []T, target T) bool {
	for _, item := range haystack {
		if item == target {
			return true
		}
	}
	return false
}

// ArrIndexOf 检查target是否在haystack中，命中则返回索引；否则返回-1
func ArrIndexOf[T comparable](haystack []T, target T) int {
	for i, str := range haystack {
		if target == str {
			return i
		}
	}

	return -1
}

// ArrUnique 去除重复元素
func ArrUnique[T int8 | int | int64 | string](haystack []T) []T {
	results := make([]T, 0, len(haystack))
	exist := map[T]struct{}{}
	for _, v := range haystack {
		_, ok := exist[v]
		if !ok {
			results = append(results, v)
			exist[v] = struct{}{}
		}
	}
	return results
}

// ArrFilterZero 去除零值元素
func ArrFilterZero[T any](haystack []T) []T {
	results := make([]T, 0, len(haystack))
	for _, v := range haystack {
		if !reflect.ValueOf(&v).Elem().IsZero() {
			results = append(results, v)
		}
	}
	return results
}

// ArrEqual 数组元素是否相同(不考虑顺序)
func ArrEqual[T comparable](a []T, b []T) bool {
	if len(a) != len(b) {
		return false
	}

	hold := make(map[T]bool)
	for _, v := range a {
		hold[v] = false
	}

	for _, v := range b {
		_, ok := hold[v]
		if !ok {
			return false
		}
		hold[v] = true
	}

	for _, v := range hold {
		if !v {
			return false
		}
	}

	return true
}

// ArrReverse 数组反转
func ArrReverse[T any](in []T) []T {
	length := len(in)
	results := make([]T, length)
	for i := range in {
		j := length - 1 - i
		results[i] = in[j]
	}
	return results
}
